<!--
 * 支付应用配置编辑页面
 * 基于 merchant-edit.vue 修改
-->

<template>
  <a-modal
    v-model:open="vdata.isShow"
    centered
    :footer="null"
    @cancel="vdata.isShow = false"
    :width="744"
    wrapClassName="app-config-modal"
    :closable="false"
  >
    <template #title>
      <div class="modal-title">
        <span class="title-icon">{{ vdata.isAdd ? '➕' : '✏️' }}</span>
        <span class="title-text">{{ vdata.isAdd ? '新增支付应用配置' : '编辑支付应用配置' }}</span>
      </div>
    </template>
    <a-form
      ref="itemForm"
      :model="vdata.itemData"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 19 }"
      layout="horizontal"
      :rules="rules"
      class="custom-form"
    >
      <a-form-item :wrapper-col="{ span: 24 }" class="form-section-title">
        <div class="section-title">基本信息</div>
      </a-form-item>

      <a-form-item label="应用ID" name="appId" v-if="vdata.isAdd">
        <a-input v-model:value="vdata.itemData.appId" placeholder="请输入应用ID" />
      </a-form-item>
      <a-form-item label="应用ID" v-else>
        <span class="readonly-text">{{ vdata.itemData.appId }}</span>
      </a-form-item>

      <a-form-item label="应用名称" name="appName">
        <a-input v-model:value="vdata.itemData.appName" placeholder="请输入应用名称" />
      </a-form-item>

      <a-form-item label="应用类型" name="appType">
        <a-select v-model:value="vdata.itemData.appType" placeholder="请选择应用类型">
          <a-select-option value="CASHIER">收银台</a-select-option>
          <a-select-option value="MOBILE">移动支付</a-select-option>
          <a-select-option value="WEB">网页支付</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="所属商户" name="merchantId">
        <a-select
          v-model:value="vdata.itemData.merchantId"
          placeholder="请选择商户"
          show-search
          :filter-option="filterMerchantOption"
          @change="handleMerchantChange"
        >
          <a-select-option
            v-for="merchant in merchantList"
            :key="merchant.merchantId"
            :value="merchant.merchantId"
          >
            {{ merchant.merchantName }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="所属服务商" name="providerId">
        <a-select v-model:value="vdata.itemData.providerId" placeholder="请选择服务商">
          <a-select-option value="">无</a-select-option>
          <a-select-option
            v-for="provider in serviceProviders"
            :key="provider.providerId"
            :value="provider.providerId"
          >
            {{ provider.providerName }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="状态" name="status">
        <a-select v-model:value="vdata.itemData.status" placeholder="请选择状态">
          <a-select-option :value="0">禁用</a-select-option>
          <a-select-option :value="1">启用</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item :wrapper-col="{ span: 24 }" class="form-section-title">
        <div class="section-title">应用配置</div>
      </a-form-item>

      <a-form-item label="应用描述" name="appDescription">
        <a-textarea v-model:value="vdata.itemData.appDescription" placeholder="请输入应用描述" :rows="3" />
      </a-form-item>

      <a-form-item label="回调地址" name="callbackUrl">
        <a-input v-model:value="vdata.itemData.callbackUrl" placeholder="请输入回调地址" />
      </a-form-item>

      <a-form-item label="通知地址" name="notifyUrl">
        <a-input v-model:value="vdata.itemData.notifyUrl" placeholder="请输入通知地址" />
      </a-form-item>
    </a-form>

    <div class="modal-footer">
      <a-button @click="vdata.isShow = false">
        取消
      </a-button>
      <a-button type="primary" :loading="vdata.confirmLoading" @click="handleOk">
        {{ vdata.isAdd ? '确认创建' : '保存' }}
      </a-button>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import { message } from 'ant-design-vue';
import type { AppConfig } from "@/mock/appconfigs";
import { generateAppId, mockSaveAppConfig } from "@/mock/appconfigs";
import { merchants, type Merchant } from "@/mock/merchants";
import { serviceProviders, type ServiceProvider } from "@/mock/service-providers";

interface State {
  isAdd: boolean;
  isShow: boolean;
  confirmLoading: boolean;
  itemData: Partial<AppConfig>;
  record: Partial<AppConfig> | null;
}

const props = defineProps({
  callbackFunc: { type: Function, default: () => {} }
});

const vdata = reactive<State>({
  isAdd: true,
  isShow: false,
  confirmLoading: false,
  itemData: {
    appId: '',
    appName: '',
    appType: '',
    merchantId: '',
    providerId: '',
    appDescription: '',
    callbackUrl: '',
    notifyUrl: '',
    status: 1
  },
  record: null
});

const itemForm = ref();
const merchantList = ref<Merchant[]>(merchants);

// 表单验证规则
const rules = {
  appId: [{ required: true, message: "请输入应用ID", trigger: "blur" }],
  appName: [{ required: true, message: "请输入应用名称", trigger: "blur" }],
  appType: [{ required: true, message: "请选择应用类型", trigger: "change" }],
  merchantId: [{ required: true, message: "请选择商户", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  callbackUrl: [
    { required: false },
    { pattern: /^https?:\/\/.+/, message: '请输入正确的URL地址', trigger: 'blur' }
  ],
  notifyUrl: [
    { required: false },
    { pattern: /^https?:\/\/.+/, message: '请输入正确的URL地址', trigger: 'blur' }
  ]
};

// 过滤商户选项
const filterMerchantOption = (input: string, option: any) => {
  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

// 商户变更处理
const handleMerchantChange = (merchantId: string) => {
  // 根据商户自动设置服务商
  const merchant = merchantList.value.find(m => m.merchantId === merchantId);
  if (merchant) {
    vdata.itemData.providerId = merchant.providerId;
  }
};

function show(record: Partial<AppConfig> | null) {
  if (itemForm.value) {
    itemForm.value.resetFields();
  }

  vdata.isAdd = !record;
  vdata.confirmLoading = false;

  if (!vdata.isAdd && record) {
    vdata.record = record;
    vdata.itemData = { ...record };
  } else {
    // 新增模式，重置为初始数据
    vdata.itemData = {
      appId: generateAppId(),
      appName: '',
      appType: '',
      merchantId: '',
      providerId: '',
      appDescription: '',
      callbackUrl: '',
      notifyUrl: '',
      status: 1,
      createdTime: '',
      updatedTime: ''
    };
  }

  vdata.isShow = true;
}

function handleOk() {
  itemForm.value.validate().then(async () => {
    vdata.confirmLoading = true;

    try {
      // 准备保存数据
      const saveData: AppConfig = {
        appId: vdata.itemData.appId!,
        appName: vdata.itemData.appName!,
        appType: vdata.itemData.appType!,
        merchantId: vdata.itemData.merchantId!,
        providerId: vdata.itemData.providerId,
        appDescription: vdata.itemData.appDescription,
        callbackUrl: vdata.itemData.callbackUrl,
        notifyUrl: vdata.itemData.notifyUrl,
        status: vdata.itemData.status!,
        createdTime: vdata.itemData.createdTime || new Date().toISOString(),
        updatedTime: new Date().toISOString()
      };

      // 模拟API调用
      await mockSaveAppConfig(saveData);

      const action = vdata.isAdd ? '创建' : '编辑';
      message.success(`${action}支付应用配置成功`);

      vdata.isShow = false;
      vdata.confirmLoading = false;
      props.callbackFunc();
    } catch (error) {
      message.error('保存失败，请重试');
      vdata.confirmLoading = false;
    }
  }).catch(() => {
    // 验证失败
  });
}

defineExpose({ show });
</script>

<style scoped>
:deep(.app-config-modal .ant-modal-content) {
  padding: 0;
  border-radius: 8px;
}

:deep(.app-config-modal .ant-modal-header) {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
  background: #fff;
  border-radius: 8px 8px 0 0;
}

.modal-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  font-size: 16px;
}

.title-text {
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

:deep(.app-config-modal .ant-modal-body) {
  padding: 24px 24px 24px 44px;
}

.custom-form {
  margin-top: 8px;
  margin-left: 41px;
}

.custom-form .ant-form-item-label > label {
  font-size: 14px;
  font-weight: 400;
  color: #8c8c8c;
  line-height: 22px;
  text-align: left;
}

.custom-form .ant-form-item-control-input-content input,
.custom-form .ant-form-item-control-input-content textarea,
.custom-form .ant-select-selector {
  font-size: 14px;
  border-radius: 6px;
  border: 1px solid #d9d9d9;
  background-color: #fff;
}

.custom-form .ant-form-item-control-input-content input,
.custom-form .ant-select-selector {
  height: 36px;
}

.custom-form .ant-form-item-control-input-content input:focus,
.custom-form .ant-select-selector:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.custom-form .ant-form-item {
  margin-bottom: 16px;
}

.custom-form .ant-form-item-label {
  padding-bottom: 0;
}

.custom-form .ant-form-item-control-input {
  max-width: 240px;
}

.form-section-title {
  margin-bottom: 16px;
  margin-top: 24px;
}

.form-section-title:first-child {
  margin-top: 0;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #262626;
  margin: 0;
  line-height: 22px;
}

.readonly-text {
  font-size: 14px;
  color: #262626;
  line-height: 22px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 32px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.modal-footer .ant-btn {
  height: 32px;
  padding: 4px 15px;
  font-size: 14px;
  border-radius: 6px;
}

:deep(.ant-form-item-label) {
  text-align: left;
}

:deep(.ant-input::placeholder),
:deep(.ant-select-selection-placeholder) {
  color: #bfbfbf;
}

:deep(.ant-textarea) {
  border-radius: 6px;
}

/* 加载状态按钮样式 */
:deep(.ant-btn-loading) {
  pointer-events: none;
}

/* 表单聚焦状态优化 */
:deep(.ant-input:focus),
:deep(.ant-textarea:focus) {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  outline: none;
}

/* 选择器样式优化 */
:deep(.ant-select:not(.ant-select-disabled):hover .ant-select-selector) {
  border-color: #40a9ff;
}

:deep(.ant-select-focused .ant-select-selector) {
  border-color: #1890ff !important;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2) !important;
}
</style>